<script setup lang="ts">
import { DataField } from '@formily/core';
import { FormItem } from '@formily/element-plus';
import { useField } from '@formily/vue';
import { Icon } from '@iconify/vue';
import { usePrefix } from '@season-designable/vue';
import cls from 'classnames';
import { defineComponent, h, ref } from 'vue';
import { ExpandedMap } from './useExpand';

const props = defineProps(['label', 'value']);
const slots = defineSlots();

const field = useField<DataField>();
const prefix = usePrefix('fold-item');

const expand = ref(ExpandedMap.get(field.value.address.toString()) || false);

const onClick = () => {
  expand.value = !expand.value;
  ExpandedMap.set(field.value.address.toString(), expand.value);
};
</script>

<template>
  <div :class="prefix">
    <div :class="prefix + '-base'" @click="onClick">
      <FormItem.BaseItem
        :label="
          defineComponent({
            setup() {
              return () =>
                h(
                  'span',
                  {
                    class: cls(prefix + '-title', {
                      expand,
                    }),
                  },
                  [
                    slots.extra && h(Icon, { icon: 'mdi:chevron-down' }),
                    props.label,
                  ]
                );
            },
          })
        "
        :class="
          cls(prefix + '-title', {
            expand,
          })
        "
      >
        <div @click.stop>
          <slot name="base"></slot>
        </div>
      </FormItem.BaseItem>
    </div>

    <div v-if="expand" :class="prefix + '-extra'">
      <slot name="extra"></slot>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import '../../../../styles.scss';
.dn-fold-item {
  :deep(.#{$formily-element-prefix}-form-item-label-content) {
    margin-left: -10px;
    // overflow: visible;
    label {
      cursor: pointer;
    }
  }

  .dn-fold-item-base {
    cursor: pointer;
  }

  :deep(.dn-fold-item-title) {
    display: flex;
    align-items: center;
    cursor: pointer;
    // .dn-icon {
    // transform: translateX(-3px);

    .dn-fold-item-title > svg {
      transition: all 0.15s ease-in-out;
      transform: rotate(-90deg);
    }
    // }

    &.expand {
      .dn-fold-item-title > svg {
        transform: rotate(0deg);
      }
    }
  }

  &-extra {
    margin-top: -10px;
    margin-left: -10px;
    margin-right: -10px;
    margin-bottom: 10px;
    padding: 10px 10px 0 10px;
    background-color: var(--dn-composite-panel-highlight-bg-color);
  }
}
</style>
